package com.ruoyi.common.core.plus.web.aop;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import com.ruoyi.common.core.plus.web.annotation.Xss;
import com.ruoyi.common.core.plus.web.annotation.XssField;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
@Aspect
public class XssAop {

    @Before(value =
            "@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
                    " || @annotation(org.springframework.web.bind.annotation.GetMapping)" +
                    " || @annotation(org.springframework.web.bind.annotation.PostMapping)" +
                    " || @annotation(org.springframework.web.bind.annotation.PutMapping)" +
                    " || @annotation(org.springframework.web.bind.annotation.DeleteMapping)" +
                    " || @annotation(org.springframework.web.bind.annotation.PathVariable)"
    )
    public void before(JoinPoint joinPoint) {
        Object[] params = joinPoint.getArgs();
        for (Object param : params) {
            if (param != null) {
                Class<?> aClass = param.getClass();
                if (aClass.isAnnotationPresent(Xss.class)) {
                    Field[] fields = aClass.getDeclaredFields();
                    for (Field field : fields) {
                        if (field.isAnnotationPresent(XssField.class)) {
                            try {
                                field.setAccessible(true);
                                Object o = field.get(param);
                                if (o instanceof String) {
                                    String filter = HtmlUtil.filter(o.toString());
                                    field.set(param, StrUtil.isEmpty(filter) ? null : filter);
                                }
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }

}
